from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework.permissions import IsAdminUser

from meiduo_admin.serializers.orders import OrderSerializer
from meiduo_admin.utils import PageNum
from orders.models import OrderInfo


class OrderView(ReadOnlyModelViewSet):
    # 指定序列化器
    serializer_class = OrderSerializer
    # 指定查询集
    queryset = OrderInfo.objects.all()
    # 指定分页器
    pagination_class = PageNum
    # 指定权限
    permission_classes = [IsAdminUser]

    # 重写获取查询集方法
    def get_queryset(self):
        if self.request.query_params.get('keyword') == '':
            return OrderInfo.objects.all()
        elif self.request.query_params.get('keyword') is None:
            return OrderInfo.objects.all()
        else:
            return OrderInfo.objects.filter(order_id__contains=self.request.query_params.get('keyword'))

    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        """
        修改订单状态
        :param request:
        :param pk: 订单id
        :return:
        """
        # 1.查询要修改的订单对象
        try:
            order = OrderInfo.objects.get(order_id=pk)
        except:
            return Response({'error': '订单id不存在'})
        # 2.修改订单状态
        # 先获取前端传来的订单状态信息
        status = request.data.get('status')
        order.status = status
        # 3.保存订单信息,返回结果
        order.save()
        return Response({'status': status, 'order_id': pk})
